package com.soup.common.exception;

import com.soup.common.constant.CommonConstant;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 通用excetion
 *
 * @author zhaoyi
 */
@Slf4j
@Getter
@ToString
public class CommonException extends RuntimeException implements Serializable {

    private static final long serialVersionUID = 3854724437287450254L;

    /**
     * 错误码
     */
    private int code;
    /**
     * 错误信息
     */
    private String message;
    /**
     * 具体的错误内容
     */
    private Object data;

    /**
     * 构建通用异常
     *
     * @param errorObj 错误对象需要包含两个方法: getCode和getMessage
     */
    public CommonException(Object errorObj) {
        // 错误对象需要包含两个方法: getCode和getMessage
        int code = CommonConstant.NUM_400;
        String msg = CommonConstant.BLANK;
        Class<?> clazz = errorObj.getClass();
        try {
            Method getCode = clazz.getMethod(CommonConstant.GETCODE);
            code = (int) getCode.invoke(errorObj);
            Method getMessage = clazz.getMethod(CommonConstant.GETMESSAGE);
            msg = (String) getMessage.invoke(errorObj);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            log.error("错误对象不符合格式，没有包含{}和{}方法", CommonConstant.GETCODE, CommonConstant.GETMESSAGE);
        }
        this.code = code;
        this.message = msg;
    }

    public CommonException(Object errorObj, Object data) {
        this(errorObj);
        this.data = data;
    }

    public CommonException(Object data, String message, int code) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public CommonException(String message, int code) {
        this.code = code;
        this.message = message;
    }

}
